/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2018年5月7日
 *******************************************************************************/

package com.hualife.md.common.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualife.md.common.dao.mybatis.entity.DefKv;
import com.hualife.md.common.dao.mybatis.mapper.DefKvMapper;
import com.hualife.md.common.dto.wx.tag.UserlistGetResponseDTO;
import com.hualife.md.common.dto.wx.tag.WeChatTagGetResponseDTO;
import com.hualife.md.common.dto.wx.user.UserlistSimplelistResponseDTO;
import com.hualife.md.common.dto.wx.user.WeChatUserSimplelistResponseDTO;
import com.hualife.md.common.service.IWeChatTagService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;
import com.hualife.support.util.HttpUtil;
import com.hualife.support.util.JsonUtil;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("weChatTagService")
public class WeChatTagServiceImpl implements IWeChatTagService {
	private static final Logger logger = LoggerFactory
			.getLogger(WeChatTagServiceImpl.class);

	@Autowired
	private DefKvMapper defKvMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.common.service.IWeChatTagService#queryTagUser(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	public List<String> queryTagUser(String tagId, String token) {

		try {
			DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.get");
			if (kv == null) {
				throw new SysException("创建标签失败，未查询到创建企业号标签配置信息");
			}
			List<String> useridList = new ArrayList<String>();

			String url = kv.getV() + "?access_token=" + token + "&tagid="
					+ tagId;
			String resultJson = HttpUtil.get(url);
			if (resultJson == null || "".equals(resultJson.trim())) {
				logger.error("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}

			WeChatTagGetResponseDTO tagResult = new WeChatTagGetResponseDTO();
			tagResult = (WeChatTagGetResponseDTO) JsonUtil.SnakeJson2CamelBean(
					resultJson, WeChatTagGetResponseDTO.class);
			if (tagResult.getErrcode() == 0) {
				if (tagResult.getUserlist() != null) {
					for (UserlistGetResponseDTO user : tagResult.getUserlist()) {
						if (user.getUserid() != null
								&& !"".equals(user.getUserid().trim()))
							useridList.add(user.getUserid().trim());
					}
				}
				if (tagResult.getPartylist() != null) {
					for (Integer partyId : tagResult.getPartylist()) {
						List<UserlistSimplelistResponseDTO> userSimList = this
								.queryDepUser(partyId.toString(), token);
						if (userSimList != null) {
							for (UserlistSimplelistResponseDTO user : userSimList) {
								if (user.getUserid() != null
										&& !"".equals(user.getUserid().trim()))
									useridList.add(user.getUserid().trim());
							}
						}
					}
				}
			}
			return useridList;
		} catch (Throwable e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	private List<UserlistSimplelistResponseDTO> queryDepUser(String depId,
			String token) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.user.simplelist");
		if (kv == null) {
			logger.error("获取部门成员失败，未查询到获取部门成员地址的配置信息！");
			throw new SysException("获取部门成员失败，未查询到获取部门成员地址的配置信息！");
		}

		String url = kv.getV() + "?access_token=" + token
				+ "&status=0&fetch_child=1&department_id=" + depId;
		try {
			String resultJson = HttpUtil.get(url);
			if (resultJson == null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}

			WeChatUserSimplelistResponseDTO userlistResult = new WeChatUserSimplelistResponseDTO();
			userlistResult = (WeChatUserSimplelistResponseDTO) JsonUtil
					.SnakeJson2CamelBean(resultJson,
							WeChatUserSimplelistResponseDTO.class);
			if (userlistResult.getErrcode() == 0) {
				return userlistResult.getUserlist();
			}
			return null;
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.common.service.IWeChatTagService#queryTagUser(java.lang
	 * .String[], java.lang.String)
	 */
	@Override
	public List<String> queryTagUser(String[] tags, String token) {

		try {
			List<String> useridList = new ArrayList<String>();
			for (int i = 0; i < tags.length; i++) {
				List<String> result = this.queryTagUser(tags[i], token);

				if (result == null)
					continue;
				else {
					useridList.addAll(result);
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.common.service.IWeChatTagService#deleteTagUser(java.lang
	 * .String, java.util.Map)
	 */
	@Override
	public void deleteTagUser(String token, Map<String, Object> paraMap) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.deluser");
		if (kv == null) {
			throw new BusinessException("创建标签失败，未查询到创建企业号标签配置信息");
		}

		String url = kv.getV() + "?access_token=" + token;
		try {
			String resultJson = HttpUtil.post(url,
					JsonUtil.objectToJackson(paraMap), 20000);
			if (resultJson == null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.common.service.IWeChatTagService#addTagUser(java.lang.
	 * String, java.util.Map)
	 */
	@Override
	public void addTagUser(String token, Map<String, Object> paraMap) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.adduser");
		if (kv == null) {
			throw new BusinessException("创建标签失败，未查询到创建企业号标签配置信息");
		}

		String url = kv.getV() + "?access_token=" + token;
		try {
			String resultJson = HttpUtil.post(url,
					JsonUtil.objectToJackson(paraMap), 20000);
			if (resultJson == null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
		}
	}

}

/*
 * 修改历史 $Log$
 */